package com.jinlejia.bbs.ui.reply;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import androidx.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.jinlejia.bbs.R;
import com.jinlejia.bbs.bean.base.InformationBean;
import com.jinlejia.bbs.bean.base.SoundBean;
import com.jinlejia.bbs.databinding.BbsActivityReplyDetailBinding;
import com.jinlejia.bbs.logic.TakeCollectionLogic;
import com.jinlejia.bbs.logic.UploadAnswerLogic;
import com.jinlejia.bbs.logic.UploadFileLogic;
import com.jinlejia.bbs.ui.fun.BBSInvitedToAnswerActivity;
import com.jinlejia.bbs.widget.BBSToast;
import com.jinlejia.bbs.widget.RecordButton;
import com.jinlejia.bbs.widget.RecordDialogManager;

import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author 王进 on 2019/4/8.
 */

public class ViewHelper {

    private final BbsActivityReplyDetailBinding binding;
    private final BBSReplyDetailActivity activity;
    private final ViewHelper.InnerRecordButtonListener soundListener;
    private final String topicCode;
    ViewHelper(BBSReplyDetailActivity activity, String topicCode,BbsActivityReplyDetailBinding binding) {
        this.activity = activity;
        this.binding = binding;
        this.topicCode = topicCode;
        this.soundListener = new ViewHelper.InnerRecordButtonListener(activity,binding.recordButton,this);
    }

    void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        boolean flag = false;
        for (int i : grantResults) {
            if (i == PackageManager.PERMISSION_GRANTED) {
                flag = true;
            } else {
                flag = false;
                break;
            }
        }
        if (flag) {

        }
    }
    private boolean isInvite;
    //endregion
    public void initView(boolean isInvite) {
        this.isInvite = isInvite;
        //region 输入框 和 输入法的设置

        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    if (binding.inputLayout.getVisibility()== View.VISIBLE){
                        binding.sendButton.setEnabled(false);
                    }
                } else {
                    if (binding.inputLayout.getVisibility()==View.VISIBLE){
                        binding.sendButton.setEnabled(true);
                    }
                }
            }
        };

        binding.inputEditText.addTextChangedListener(watcher);
        binding.inputLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeIme();
                hideInputLayout();
                hideReplyLayout();
            }
        });
        binding.recordButton.setRecordActionListener(soundListener);
        //endregion

    }


    public void answer(View view) {
        showInputLayout();
    }

    void showInputLayout(){
        binding.inputLayout.setVisibility(View.VISIBLE);
        binding.inputEditText.postDelayed(new Runnable() {
            @Override
            public void run() {
                openIme();
            }
        }, TimeUnit.SECONDS.toMillis((long) 0.5));
    }

    void hideInputLayout(){
        binding.inputLayout.setVisibility(View.GONE);
    }

    void hideReplyLayout(){
        binding.inputLayout.setVisibility(View.GONE);
    }

    public void changeInputType(View view) {
        if (binding.recordButton.getVisibility() == View.VISIBLE) {
            //隐藏录音按钮
            binding.recordButton.setVisibility(View.GONE);
            //展示文本输入按钮
            binding.inputEditText.setVisibility(View.VISIBLE);
            binding.sendButton.setVisibility(View.VISIBLE);
            if (binding.inputEditText.getText().length() != 0) {
                binding.sendButton.setEnabled(true);
            } else {
                binding.sendButton.setEnabled(false);
            }
            binding.inputEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    openIme();
                }
            }, TimeUnit.SECONDS.toMillis((long) 0.5));
        } else {
            //展示 录音按钮
            binding.recordButton.setVisibility(View.VISIBLE);
            //隐藏，文本输入
            binding.inputEditText.setVisibility(View.GONE);
            binding.sendButton.setVisibility(View.GONE);
            binding.inputEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    closeIme();
                }
            }, TimeUnit.SECONDS.toMillis((long) 0.5));
        }
    }

    public void toInvitedToAnswerActivity(View view) {
        Intent intent = new Intent();
        intent.setClass(activity, BBSInvitedToAnswerActivity.class);
        intent.putExtra("topicCode",topicCode);
        activity.startActivity(intent);
    }

    void onActivityResult(int requestCode, int resultCode, Intent data){

    }

    private TakeCollectionLogic collectionLogic;
    public void collect(View view) {
        if (collectionLogic==null){
            collectionLogic = new TakeCollectionLogic(activity);
        }
        collectionLogic.execute(topicCode, new TakeCollectionLogic.LogicCallBack() {
            @Override
            public void onResult(boolean result) {
                if (result){
                    binding.collectImg.setImageResource(R.mipmap.bbs_icon_liked_button);
                    binding.collectTextView.setText("已收藏");
                    binding.collectTextView.setTextColor(Color.parseColor("#FCCB00"));
                }else {
                    binding.collectImg.setImageResource(R.mipmap.bbs_icon_like_button);
                    binding.collectTextView.setTextColor(Color.parseColor("#333333"));
                    binding.collectTextView.setText("收藏");
                }
            }
        });
    }

    //region 发送文本消息体
    private UploadAnswerLogic logic;
    private long checkTime;
    public void sendMessage(View view){
        long millis = System.currentTimeMillis() - checkTime;
        long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
        if (seconds<=1){ //一秒内不允许重复点击
            return;
        }
        checkTime = System.currentTimeMillis();
        if (logic==null){
            logic = new UploadAnswerLogic(activity);
        }
        InformationBean bean = new InformationBean();
        Editable text = binding.inputEditText.getText();
        if (text.length()<8){
            BBSToast.showToast(activity,"最少输入8个字符",1500);
            return;
        }
        bean.setMessageContent(text.toString());
        logic.execute(isInvite,topicCode, bean, new UploadAnswerLogic.LogicCallBack() {
            @Override
            public void onResult(boolean flag) {
                if (flag){ //提交成功后，关闭输入布局
                    binding.inputEditText.setText(null);
                    closeIme();
                    activity.onRefresh();
                    hideInputLayout();
                    hideReplyLayout();
                }
            }
        });
    }
    //endregion
    //region 发送声音消息体
    private void sendSound(String soundContent){
        long millis = System.currentTimeMillis() - checkTime;
        long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
        if (seconds<=1){ //一秒内不允许重复点击
            return;
        }
        checkTime = System.currentTimeMillis();
        if (logic==null){
            logic = new UploadAnswerLogic(activity);
        }
        InformationBean bean = new InformationBean();
        bean.setSoundContent(SoundBean.create(soundContent));
        logic.execute(isInvite,topicCode, bean, new UploadAnswerLogic.LogicCallBack() {
            @Override
            public void onResult(boolean flag) {
                if (flag){ //提交成功后，关闭输入布局
                    binding.inputEditText.setText(null);
                    activity.onRefresh();
                    closeIme();
                    hideInputLayout();
                    hideReplyLayout();
                }
            }
        });
    }
    //endregion


    private void openIme() {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        binding.inputEditText.requestFocus();
        if (imm != null){
            if (binding.inputLayout.getVisibility()==View.VISIBLE){
                imm.showSoftInput(binding.inputEditText, InputMethodManager.SHOW_FORCED);
            }
        }
    }

    private void closeIme() {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            if (binding.inputLayout.getVisibility()==View.VISIBLE){
                imm.hideSoftInputFromWindow(binding.inputEditText.getWindowToken(),0);
            }
        }
    }

    public void release() {
        hideKeyboard();
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm==null)return;
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    private static class InnerRecordButtonListener implements RecordButton.RecordActionListener, RecorderHelper.RecorderListener {
        private RecordDialogManager dialogManager;
        private final AtomicBoolean mCancel = new AtomicBoolean(false);
        private final AtomicBoolean mIsMax = new AtomicBoolean(false); //true:达到了最大长度 false:没有
        private final RecorderHelper helper;
        private final Context context;
        private final RecordButton recordButton;
        private final ViewHelper viewHelper;
        InnerRecordButtonListener(Context context, RecordButton recordButton, ViewHelper viewHelper){
            this.context = context;
            helper = RecorderHelper.instance();
            helper.init(context);
            helper.setRecorderListener(this);
            this.recordButton = recordButton;
            this.dialogManager = new RecordDialogManager(context);
            this.viewHelper = viewHelper;
        }

        private boolean requestPermissions() {
            Activity activity = (Activity) context;
            if (Build.VERSION.SDK_INT >= 23) {
                int REQUEST_CODE_CONTACT = 101;
                String[] permissions = {Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                //验证是否许可权限
                for (String str : permissions) {
                    if (activity.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                        //申请权限
                        activity.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        return false;
                    }
                }
            }
            return true;
        }

        @Override
        public void onStartRecorder() {
            boolean permissions = requestPermissions();
            if (permissions){
                recordButton.setTouchEnable(true);
                dialogManager.recording();
                helper.start();
            }else {
                recordButton.setTouchEnable(false);
            }
        }

        @Override
        public void onStopRecorder(boolean cancel) {
            mCancel.set(cancel);
            if (!mIsMax.get()){ //如果是最大长度，则不作处理
                helper.stop(false);
                dialogManager.dismissDialog();
            }

        }

        @Override
        public void onCancelRecorder(boolean cancel) {
            if (cancel) {
                dialogManager.wantToCancel();
            } else {
                dialogManager.recording();
            }
        }


        private long time;
        private int oldSeconds = 0;
        @Override
        public void onStart() {
            mIsMax.set(false);
            time = System.currentTimeMillis();
        }
        private UploadFileLogic fileLogic;
        @Override
        public void onStop(File file,boolean isMax) {
            if (mCancel.get()) { //取消的文件，进行删除
                file.deleteOnExit();
                return;
            }
            long millis = System.currentTimeMillis() - time;
            long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
            oldSeconds = (int) seconds;//已经录制 秒
            if (oldSeconds < 1) { //录制不足一秒的进行删除
                dialogManager.tooShort();
                file.deleteOnExit();
                return;
            }
            if (dialogManager.isShow()){ //尝试关闭对话框
                dialogManager.dismissDialog();
            }
            //录制成功
            if (fileLogic==null){
                fileLogic = new UploadFileLogic(context);
            }
            fileLogic.execute(file, new UploadFileLogic.LogicCallback() {
                @Override
                public void onResult(String fileName, String severPath) {
                    viewHelper.sendSound(severPath);
                }
            });
        }

        @Override
        public void onVolume(int volume) {
            dialogManager.updateVoiceVolume(volume);
        }
    }
}
